package com.itheima.web;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;

import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping(path = "/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/findAll")
    public String findAll(Model model, @RequestParam(name = "page", required = true, defaultValue = "1") int page
            , @RequestParam(name = "pageSize", required = true, defaultValue = "4") int pageSize) {
        List<Role> roleList = roleService.findAll(page, pageSize);
        PageInfo pageInfo = new PageInfo(roleList);
        model.addAttribute("roleList", pageInfo);
        return "role-list";
    }

    @RequestMapping("/save")
    public String save(Role role) {

        int num = roleService.save(role);
        if (num != 0) {
            return "redirect:/role/findAll";
        }
        return "role-add";
    }
    @RequestMapping("/findById")
    public String findById(Model model, String id) {

        Role role = roleService.findById(id);

        model.addAttribute("role", role);
        return "role-show";

    }
    @RequestMapping("/findUserByIdAndAllRole")
    public String findUserByIdAndAllRole(Model model, String id) {

        //获取角色详情
        Role role = roleService.findById(id);
//        获得还允许添加的权限
        List<Permission> permissionList = roleService.findRoleNotPermission(id);
             model.addAttribute("role", role);
        model.addAttribute("permissionList", permissionList);
        return "role-permission-add";
//        addPermissionToRole
    }
    @RequestMapping("/addPermissionToRole")
    public String addPermissionToRole(@RequestParam(name = "roleId",required = true) String roleId,@RequestParam(name = "ids" ,required = true) String[] ids) {


                int number = roleService.addPermissionToRole(roleId,ids);

//        判断是否成功，用于返回对应的页面
        if (number != 0) {
            return "redirect:/role/findAll";
        }
        return "role-permission-add";
    }
}

